package com.scu.qingshi.listener;

import com.google.common.eventbus.Subscribe;
import com.scu.qingshi.config.cummunity.CommunityConfig;
import com.scu.qingshi.config.cummunity.CommunityFactory;
import com.scu.qingshi.domain.authorize.model.AuthorizationEmailMessage;
import com.scu.qingshi.domain.interview.event.NodeFailEvent;
import com.scu.qingshi.domain.interview.event.NodePassEvent;
import com.scu.qingshi.domain.interview.event.NoticeNextNodeEvent;
import com.scu.qingshi.infrastructure.dao.po.Node;
import com.scu.qingshi.infrastructure.dao.po.User;
import com.scu.qingshi.infrastructure.dao.service.NodeService;
import com.scu.qingshi.infrastructure.dao.service.UserService;
import com.scu.qingshi.infrastructure.event.EventBusCenter;
import com.scu.qingshi.infrastructure.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 面试结果监听器
 * @author qingshi
 */
@Component
public class JudgeEventListener {

    @Autowired
    EventBusCenter eventBusCenter;

    @Autowired
    NodeService nodeService;

    @Autowired
    UserService userService;

    @Autowired
    EmailUtil emailUtil;

    @PostConstruct
    void init(){
        eventBusCenter.register(this);
    }

    @Subscribe
    void listenJudgeResult(NodePassEvent event){

        Node node = nodeService.getById(event.getNodeId());

        User user = userService.getById(event.getUserId());
        CommunityConfig community = CommunityFactory.getCommunity(event.getOpenId());
        emailUtil.sendEmail(
                community.getEmail(),
                user.getEmail(),
                "来自"+community.getName()+"的通知邮件",
                node.getInformPass()
        );

    }

    @Subscribe
    void listenJudgeResult(NodeFailEvent event){

        Node node = nodeService.getById(event.getNodeId());

        User user = userService.getById(event.getUserId());
        CommunityConfig community = CommunityFactory.getCommunity(event.getOpenId());
        emailUtil.sendEmail(
                community.getEmail(),
                user.getEmail(),
                "来自"+community.getName()+"的通知邮件",
                node.getInformFail()
        );

    }

    @Subscribe
    void listenJudgeResult(NoticeNextNodeEvent event){

        Node node = nodeService.getById(event.getNodeId());

        User user = userService.getById(event.getUserId());
        CommunityConfig community = CommunityFactory.getCommunity(event.getOpenId());
        emailUtil.sendEmail(
                AuthorizationEmailMessage.FROM,
                user.getEmail(),
                "来自"+community.getName()+"的面试通知邮件",
                node.emailTemplate()
        );

    }

}
